<template>
	<div ref="container">
		<slot></slot>
		<Teleport to="body">
			<Transition v-on:before-enter="beforeEnter" v-on:enter="enter" v-on:after-enter="afterEnter">
				<div class="context-menu" v-show="show" :style="{ left: position.x + 'px', top: position.y + 'px' }">
					<div class="context-menu-item" v-for="(item, index) in menu" :key="index">
						<div @click="handleClick(item)">{{ item.label }}</div>
					</div>
				</div>
			</Transition>
		</Teleport>
	</div>
</template>
<script>
import Teleport from '@/components/teleport'
export default {
	name: 'ContextMenu',
	components: {
		Teleport
	},
	props: {
		menu: {
			type: Array,
			default: () => []
		}
	},
	data() {
		return {
			// 菜单是否显示
			show: false,
			// 菜单位置
			position: {
				x: 0,
				y: 0
			}
		}
	},
	methods: {
		// 菜单点击事件
		handleClick(item) {
			this.$emit('click', item)
		},
		// 显示菜单
		showMenu(e) {
			e.preventDefault()
			e.stopPropagation()
			this.show = true
			// 获取菜单位置
			this.position.x = e.clientX
			this.position.y = e.clientY
		},
		// 隐藏菜单
		hideMenu() {
			this.show = false
		},
		beforeEnter: function (el) {
			el.style.height = 0
		},
		enter: function (el) {
			el.style.height = 'auto'
			const h = el.clientHeight
			el.style.height = 0
			requestAnimationFrame(() => {
				requestAnimationFrame(() => {
					el.style.height = h + 'px'
					el.style.transition = '.5s'
				})
			})
		},
		afterEnter: function (el) {
			el.style.height = 'auto'
			el.style.transition = 'none'
		}
	},
	mounted() {
		console.log(1)
		console.log(this.$refs.container)
		this.$refs.container.addEventListener('contextmenu', this.showMenu)
		window.addEventListener('click', this.hideMenu, true)
		window.addEventListener('contextmenu', this.hideMenu, true)
	},
	beforeDestroy() {
		this.$refs.container.removeEventListener('contextmenu', this.showMenu)
		window.removeEventListener('click', this.hideMenu, true)
		window.removeEventListener('contextmenu', this.hideMenu, true)
	}
}
</script>
<style lang="less" scoped>
.context-menu {
	position: fixed;
	z-index: 2000;
	background-color: #fff;
	border: 1px solid #ebebeb;
	overflow: hidden;
	border-radius: 4px;
	box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
	padding: 16px 0;
	.context-menu-item div {
		line-height: 30px;
		padding: 0 16px;
		min-width: 104px;
		list-style: none;
		color: #606266;
		cursor: pointer;
		outline: 0;
		&:hover,
		&:focus {
			background-color: #f0faff;
			color: #2d8cf0;
		}
	}
}
</style>
